<?php
/**
 * Created by PhpStorm.
 * User: zhangxilu
 * Date: 2018/4/23
 * Time: 下午10:06
 */

namespace frontend\modules\v1\controllers;


use common\logic\CouponLogic;
use common\logic\PayNotifyCallBack;
use common\logic\UserCouponLogic;
use common\models\UserOrderModel;
use common\models\UserModel;
use common\wx\JsApiPay;
use common\wx\NativePay;
use common\wx\WxPayApi;
use common\wx\WxPayConfig;
use common\wx\WxPayUnifiedOrder;
use frontend\common\ApiController;
use common\logic\PayRedpacketCallBack;

class CouponController extends ApiController
{
    public $enableCsrfValidation = false;

    public function actionList()
    {
        $page = $this->getPage();

        $pageSize = $this->getPageSize();
        $data = CouponLogic::instance()->getByPage($page, $pageSize);

        return $this->success($data);
    }


    public function actionMyList()
    {
        $uid = \Yii::$app->request->get('uid');
        $page = $this->getPage();

        $pageSize = $this->getPageSize();
        $data = UserCouponLogic::instance()->getByPage($page, $uid, $pageSize);

        return $this->success($data);
    }


    public function actionPay($uid, $id)
    {


    }


    public function actionBuy($uid, $cid, $openId)
    {
        $coupon = CouponLogic::instance()->getById($cid);
        if (empty($coupon)) {
            return $this->error('优惠券不存在');
        }

        list($time1, $time2) = explode(' ', microtime());

        $order_sn = date('YmdHis', $time2) . str_pad(($time1 * 1000000), 7, '0') . str_pad(rand(10000000000, 99999999999), 11, '0');

        $model = new UserOrderModel();
        $model->order_sn = $order_sn;
        $model->create_time = time();
        $model->user_id = $uid;
        $model->coupon_id = $cid;

        if ($model->save()) {
            //①、获取用户openid
            $tools = new JsApiPay();
            //②、统一下单
            $input = new WxPayUnifiedOrder();
            $input->SetBody($coupon->name);
            $input->SetOut_trade_no($order_sn);
            $input->SetTotal_fee($coupon->amount * 100);
            $input->SetTime_start(date("YmdHis"));
            $input->SetNotify_url(FRONTEND_URL . "/v1/coupon/call-back");
            $input->SetTrade_type("JSAPI");
            $input->SetOpenid($openId);
            $order = WxPayApi::unifiedOrder($input);
            $jsApiParameters = $tools->GetJsApiParameters($order);

            //获取共享收货地址js函数参数
            $editAddress = $tools->GetEditAddressParameters();


            return $this->success(['order' => $order, 'jsApiParameters' => $jsApiParameters, 'editAddress' => $editAddress]);
        }

        return $this->error('提交订单失败');
    }

    public function actionBuyQrcode($uid, $cid){

        $coupon = CouponLogic::instance()->getById($cid);
        if (empty($coupon)) {
            return $this->error('优惠券不存在');
        }

        $user = UserModel::findOne(['id' => $uid]);
        if (empty($user)) {
            return $this->error('用户信息不存在');
        }
        $openId = $user->pcopenid;
        if($openId == null || $openId == ''){
            $openId = $user->openid;
        }

        list($time1, $time2) = explode(' ', microtime());

        $order_sn = date('YmdHis', $time2) . str_pad(($time1 * 1000000), 7, '0') . str_pad(rand(10000000000, 99999999999), 11, '0');

        $model = new UserOrderModel();
        $model->order_sn = $order_sn;
        $model->create_time = time();
        $model->user_id = $uid;
        $model->coupon_id = $cid;

        if ($model->save()) {
            //①、获取用户openid
            $tools = new JsApiPay();
            //②、统一下单
            $input = new WxPayUnifiedOrder();
            $input->SetBody($coupon->name);
            $input->SetOut_trade_no($order_sn);
            $input->SetTotal_fee($coupon->amount * 100);
            $input->SetTime_start(date("YmdHis"));
            $input->SetNotify_url(FRONTEND_URL . "/v1/coupon/qrcode-back");
            $input->SetTrade_type("NATIVE");
            $input->SetOpenid($openId);
            $input->SetProduct_id($cid);
            $notify = new NativePay();
		    $result = $notify->GetPayUrl($input);

            return $this->success(['oid'=>$model->id,'order'=>$result]);
        }

        return $this->error('提交订单失败');
    }

    public function actionCallBack()
    {
        $notify = new PayNotifyCallBack();
        $notify->Handle(false);
        exit;
    }

    public function actionOrderState()
    {
        $oid = \Yii::$app->request->get('oid');
        if(!empty($oid)){
            $orders = UserOrderModel::findOne(['id' => $oid]);
            if (empty($orders)) {
                return $this->error('订单不存在');
            }
            return $this->success(['pay_status'=>$orders->pay_status]);
        }  
        return $this->error('参数错误');
    }

    public function actionQrcodeBack()
    {
        $notify = new PayNotifyCallBack();
        $notify->Handle(false);
        exit;
    }

    public function actionRedBack()
    {
//      $db = \Yii::$app->db;
//      $getuser = $db->createCommand("insert into ph_errorlog(msg)values('test back')")->execute();

        $notify = new PayRedpacketCallBack();
        $notify->Handle(false);
        exit;

    }

}